package com.servlet.yanglaoyuan.controller;

import com.servlet.yanglaoyuan.common.Result;
import com.servlet.yanglaoyuan.pojo.Elderly;
import com.servlet.yanglaoyuan.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.servlet.yanglaoyuan.service.userService;

import java.util.Map;

@Slf4j
@RestController
public class userController {
    @Autowired
    private userService userService;
    //绑定老人给用户
    @PutMapping("/user/bind/{userId}/{elderlyId}")
    public Result bindElderly(@PathVariable Long userId,@PathVariable  Long elderlyId){
        userService.bindElderly(userId,elderlyId);
        return Result.success();
    }

    /*
      用户注册，添加用户
     */
    @PostMapping("/regUser")
    public Result addUser(@RequestBody User user){
        userService.addUser(user);
        return Result.success();
    }
    //删除用户
    @DeleteMapping("/user/{id}")
    public Result deleteUser(@PathVariable Long id){
        userService.deleteUser(id);
        return Result.success();
    }
    //更新用户信息
    @PutMapping("/user")
    public Result updateUser(@RequestBody User user){
        log.info("更新用户信息：{}",user);
        userService.updateUser(user);
        return Result.success();
    }

    //根据用户名和密码查询用户
    @PostMapping("/loginUser")
    public Result findByNameAndPassword(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");

        User user = userService.findByNameAndPassword(username, password);
        if (user == null) {
            return Result.error("用户名或密码错误");
        }
        return Result.success(user);
    }
    //根据ID查询用户
    @GetMapping("/user/{id}")
    public Result findById(@PathVariable Integer id){
        //id类型从Integer到Long
        Long userid = Long.valueOf(id);

        User user = userService.findById(userid);
        return Result.success(user);
    }
}
